package com.copro.chemdb.constants;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.ihelpuoo.db.sql.SQLSegment;
import org.ihelpuoo.lang.NumericUtils;

import com.copro.simple.Application;

public class SaveConstAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Application app = Application.me(request);
		int id = NumericUtils.parseInt(request.getParameter("id"), 0);
		String name = request.getParameter("name");
		ConstType constType= new ConstType();
		constType.setId(id);
		constType.setName(name);
		// Old
		if (id > 0) {
			SQLSegment sql = app.getSQL("updateConstType");
			sql.set("id", id);
			sql.set("name", name);
			app.exec(sql.toString());
			//remove all the value list
			sql = app.getSQL("delConstValues");
			sql.set("id", id);
			app.exec(sql.toString());
		} else {
			SQLSegment sql = app.getSQL("newConstType");
			sql.set("name", name);
			app.insert(sql.toString(), "maxConstType", constType, "id");
		}
		//insert the values
		List<ConstValue> constValues = new ArrayList<ConstValue>();
		String[] constValueNames = request.getParameterValues("constValue");
		ConstValue constValue = null;
		for(int i = 0; i < constValueNames.length; i++){
			try{
				constValue = new ConstValue();
				constValue.setId_L_type(constType.getId());
				constValue.setName(constValueNames[i]);
				constValues.add(constValue);
				SQLSegment sql = app.getSQL("newConstValue");
				sql.fillBy(constValue);
				app.exec(sql.toString());
			}catch(NumberFormatException e){
				//do nothing
			}
		}

		request.setAttribute("constType", constType);
		request.setAttribute("constValueSet", constValues);
		return mapping.findForward("edit");
	}

}
